﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using LERP.Domain;
using LERP.Domain.Enums;
using LERP.Web.Controllers.ViewModels.UserViewModels;
using Sharp.Framework;
using Sharp.Framework.Queries;
using SharpArch.NHibernate.Web.Mvc;
using Sharp.Framework.Extensions;

namespace LERP.Web.Controllers
{
    public class UserController : BaseController
    {

        private readonly IQuery _query;

        public UserController(IQuery query)
        {
            _query = query;
        }
         

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="role"></param>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index(int? role, string keyword, int page = 1, int size = 12)
        { 
            var query = _query.FindAll<User>().Where(m => m.Stauts == DataStatus.Normal&&m.Role!=UserRole.System);
             
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(m => m.Name.Contains(keyword));
            }

            if (role.HasValue)
            {
                query = query.Where(m => m.Role==(UserRole)role.Value);
            }
            var model = query.OrderByDescending(m => m.Modified).Select(m => new UserViewModel
            {
                Id = m.Id,
                Name = m.Name,
                Email = m.Email,
                Mobile = m.Mobile,
                Role = (int)m.Role,
                UserName = m.UserName, 
            }).ToPagedList(page, size);

            ViewBag.Roles = GetUserRoles();
            return View(model);
        }
        /// <summary>
        /// 获取用户角色列表
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GetUserRoles()
        {
            return UserRole.Admin.ToDictionary().Where(m => m.Value != (int)UserRole.System).Select(
                    m => new SelectListItem { Text = m.Key, Value = m.Value.ToString(CultureInfo.InvariantCulture) }).ToList();
        }


        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
          [HttpGet]
        public ActionResult Details(int id)
        {
            var model = _query.Get<User>(id);
            if (null == model)
            {
                return View("NoFound");
            }
            return View(model);
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {

            ViewBag.Roles = GetUserRoles();
            return View(new CreateUserViewModel());
        } 

        /// <summary>
        /// 提交 新增用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        public ActionResult Create(CreateUserViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new User
                                     {

                                         Stauts = DataStatus.Normal,
                                         Created = DateTime.Now,
                                         Modified = DateTime.Now,
                                         Role = (UserRole) model.Role,
                                         Functions =
                                             int.Parse(
                                                 System.Configuration.ConfigurationManager.AppSettings[
                                                     ((UserRole) model.Role) == UserRole.Admin
                                                         ? "admin_role_function"
                                                         : "user_role_function"]),
                                         Name = model.Name,
                                         UserName = model.UserName,
                                         Email = model.Email,
                                         Mobile = model.Mobile,
                                         Password =
                                             FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password,
                                                                                                    "MD5")
                                     };
                    _query.Save(entity);
                    return RedirectToAction("Index", "User");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }

            ViewBag.Roles = GetUserRoles();
            return View(model);
        }

       /// <summary>
       /// 修改用户
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var model = _query.Get<User>(id);
            if (null == model)
            {
                return View("NoFound");
            }
           var user = new ModifyUserViewModel
               { 
                   Name = model.Name,
                   UserName = model.UserName,
                   Email = model.Email,
                   Mobile = model.Mobile,
                   Role = (int)model.Role
               };
           ViewBag.Roles = GetUserRoles();
           return View(user); 
        }

        /// <summary>
        /// 修改用户 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult Edit(int id, ModifyUserViewModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var user = _query.Get<User>(id);
                    if (null == user)
                    {
                        return View("NoFound");
                    }  
                    user.Name = model.Name; 
                    user.Email = model.Email;
                    user.Mobile = model.Mobile;
                    user.Modified = DateTime.Now; 
                    _query.Save(user); 
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }

            ViewBag.Roles = GetUserRoles();
            return View();
        }

       /// <summary>
       /// 重置密码
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        public ActionResult ResetPassword(int id)
        {
            var model = _query.Get<User>(id);
            if (null == model)
            {
                return View("NoFound");
            }
           var user = new ResetPasswordViewModel
               {  
                   UserName = model.UserName
               }; 
           return View(user); 
        }

        /// <summary>
        /// 重置密码 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult ResetPassword(int id, ResetPasswordViewModel model, string returnUrl)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var user = _query.Get<User>(id);
                    if (null == user)
                    {
                        return View("NoFound");
                    }
                    user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5");
                    user.Modified = DateTime.Now;
                    _query.Save(user);
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
             
            return View();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [Transaction]
        [HttpGet]
        public ActionResult Delete(int id, string returnUrl)
        {
            var entity = _query.Get<User>(id);

            if (null == entity)
            {
                return View("NoFound");
            } 
            entity.Stauts= DataStatus.Deleted;
            _query.Save(entity);
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Index");
            }
            return Redirect(returnUrl);
        }
       /// <summary>
       /// 用户资料维护
       /// </summary> 
       /// <returns></returns>
        public ActionResult Profile()
        {
            var model = _query.Get<User>(Current.Id);
            if (null == model)
            {
                return View("NoFound");
            }
           var user = new ModifyUserViewModel
               {  
                   UserName = model.UserName,
                   Email = model.Email,
                   Mobile = model.Mobile,
                   Name = model.Name
               }; 
           return View(user); 
        }

        /// <summary>
        /// 用户资料维护 提交
        /// </summary> 
        /// <param name="model"></param> 
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult Profile( ModifyUserViewModel model)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var user = _query.Get<User>(Current.Id);
                    if (null == user)
                    {
                        return View("NoFound");
                    }

                    user.Name = model.Name;
                    user.Email = model.Email;
                    user.Mobile = model.Mobile;
                    user.Modified = DateTime.Now; 
                    user.Modified = DateTime.Now;
                    _query.Save(user); 
                    return RedirectToAction("Profile");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
             
            return View();
        } 
        /// <summary>
        /// 用户修改密码
       /// </summary> 
       /// <returns></returns>
        public ActionResult ChangePassword()
        {
            var model = _query.Get<User>(Current.Id);
            if (null == model)
            {
                return View("NoFound");
            }
            var user = new ChangePasswordViewModel
               {  
                   UserName = model.UserName
               }; 
           return View(user); 
        }

        /// <summary>
        /// 用户修改密码 提交
        /// </summary> 
        /// <param name="model"></param> 
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            try
            {

                if (ModelState.IsValid)
                {

                    var user = _query.Get<User>(Current.Id);
                    if (null == user)
                    {
                        return View("NoFound");
                    }
                     if (user.Password !=
                         FormsAuthentication.HashPasswordForStoringInConfigFile(model.OldPassword, "MD5"))
                     {

                         ModelState.AddModelError("OldPassword", "旧密码输入错误,请重新输入");
                     }
                    user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5");
                    user.Modified = DateTime.Now;
                    _query.Save(user); 
                    return RedirectToAction("Profile");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
             
            return View();
        }
    }
}
